<html>
	<head>
		<script src="../gears_init.js"></script>
		<script src="../GearsORM.js"></script>
		<script src="../GearsORM.Events.js"></script>
		<script src="../GearsORM.ResultIterator.js"></script>
		<script src="../GearsORM.Sql.js"></script>
		<script src="../GearsORM.Fields.js"></script>
		<script src="../GearsORM.Model.js"></script>
		<script src="../GearsORM.Introspection.js"></script>
		<script src="../GearsORM.Transaction.js"></script>
		<script>
			GearsORM.dbName = "test.m2m";
			var Tag = new GearsORM.Model({
				name:"Tag",
				fields:
				{
					name:new GearsORM.Fields.String({maxLength:20}),
					posts:new GearsORM.Fields.ManyToMany({related:"Post"})
				}
			});
			var Post = new GearsORM.Model({
				name:"Post",
				fields:
				{
					title:new GearsORM.Fields.String({maxLength:50}),
					body:new GearsORM.Fields.String({maxLength:5000}),
					tags:new GearsORM.Fields.ManyToMany({related:"Tag"})
				}
			});
			
			var Tests =
			{
				up:function()
				{
					Post.dropTable();
					Tag.dropTable();
					Post.createTable();
					Tag.createTable();
					new Post({title:"test post",body:"test body"}).save();
					new Tag({name:"test tag"}).save();
				},
				"test if select works with ManyToMany relation":function()
				{
					//create relation Post<=>Tag
					var post = Post.select().getOne();
					var tag = Tag.select().getOne();
					
					post.tags.add(tag);
					UnitTest.assertTrue(
						post.tags.select().toArray().length == 1 && tag.posts.select().toArray().length == 1,
						"relation between tag<=>post wasn`t created"
					);
				},
				"test if remove works with ManyToMany relation":function()
				{
					var post = Post.select().getOne();
					var tag = Tag.select().getOne();
					post.tags.remove(tag);
					UnitTest.assertTrue(
						post.tags.select().toArray().length == 0 && tag.posts.select().toArray().length == 0,
						"relation between tag<=>post wasn`t deleted"
					);
				},
				"test if m2m forigen keys are enforced":function()
				{
					var post = Post.select().getOne();
					var newTag = new Tag({name:"test new tag",rowid:10});
					//insert
					try
					{
						post.tags.add(newTag);
					}
					catch(e)
					{
						return;
					}
					//delete
					try
					{
						post.tags.remove(newTag);
					}
					catch(e)
					{
						return;
					}
					throw new Error("a exception didn`t happen even that the insert or delete vaiolate the forigen key");
				},
				down:function()
				{
					Post.dropTable();
					Tag.dropTable();
				}
			};
		</script>
		<script src="unit_test.js"></script>
	</head>
	<body>
		
	</body>
</html>